import java.io.*;
import java.util.Scanner;
//扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
public class demo9 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径:");
        String rootPath = scanner.next();
        System.out.println("请输入要查询的词:");
        String searchWord = scanner.next();

        //构造File对象,检查路径是否合理.
        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()){
            System.out.println("输入的路径非法!");
            return;
        }
        //进行递归搜索.
        searchFile(rootFile,searchWord);
    }
    private static void searchFile(File rootFile, String searchWord) {
        //1. 列出当前目录中有哪些内容
        File[] files = rootFile.listFiles();
        if (files == null){
            //空目录直接返回
        }
        // 2. 遍历目录下的每个结果, 进行判定
        for(File f : files){
            // 普通文件, 就判定文件名是否包含 查询词.
            if (f.isFile()){
               matchWord(f,searchWord);
            } else if (f.isDirectory()) {
                searchFile(f,searchWord);
            }
        }
    }

    private static void matchWord(File f, String searchWord) {
        try(Reader reader = new FileReader(f)) {
            StringBuilder strigBuilder = new StringBuilder();
            while(true){
                int c = reader.read();
                if(c == -1){
                    break;
                }
                strigBuilder.append((char) c);
            }
            if (strigBuilder.indexOf(searchWord) >= 0){
                System.out.println("找到了匹配的结果" + f.getAbsolutePath());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
